package cn.bdqn.t230.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bdqn.t230.pojo.PageBean;
import cn.bdqn.t230.pojo.User;
import cn.bdqn.t230.service.UserService;
import cn.bdqn.t230.util.StringUtils;

@WebServlet("/users")
public class UserServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		UserService userService = new UserService();
		String pageNo = req.getParameter("pageNo");
		if(StringUtils.isEmpty(pageNo)) pageNo = "1";
		
		String pageSize = req.getParameter("pageSize");
		if(StringUtils.isEmpty(pageSize)) pageSize = "2";
		
		String userName = req.getParameter("userName");
		String[] userRoles = req.getParameterValues("userRoles");
		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("userName", userName);
		params.put("userRoles", userRoles);
		
		String findBy = req.getParameter("findBy");
		List<User> list = null;
		if("findAll".equals(findBy)) {
			PageBean<User> pageBean = new PageBean<User>();
			pageBean.setPageNo(Integer.parseInt(pageNo));
			pageBean.setPageSize(Integer.parseInt(pageSize));
			userService.findByMap(pageBean, params);
			req.setAttribute("pageBean", pageBean);
			req.setAttribute("params", params);
		} else {
			User user = new User();
			user.setUserName(userName);
			list = userService.findByUser(user, userRoles);
		}
		req.setAttribute("list", list);
		req.setAttribute("userName", userName);
		req.setAttribute("userRoles", Arrays.asList(userRoles));
		req.setAttribute("findBy", findBy);
		req.getRequestDispatcher("/index.jsp").forward(req, resp);
	}
}
